import { defineStore } from 'pinia';
import { ref, reactive } from 'vue';
import Cookies from 'js-cookie';
import { RouteRecordRaw } from 'vue-router';
import router from '@/router';

export const useUserStore = defineStore('user', () => {
  // 初始化时从localStorage恢复token
  const initToken = () => {
    const savedToken = localStorage.getItem('token');
    if (savedToken) {
      token.value = savedToken;
    }
  };

  // 初始化token
  initToken();
  // 初始化用户信息
  const initUserInfo = () => {
    const savedUserInfo = localStorage.getItem('userInfo');
    if (savedUserInfo) {
      try {
        const parsedUserInfo = JSON.parse(savedUserInfo);
        Object.assign(userInfo, parsedUserInfo);
      } catch (error) {
        console.error('解析用户信息失败:', error);
      }
    }
  };

  // 初始化用户信息
  initUserInfo();
  // 用户信息
  const userInfo = reactive({
    id: '',
    name: '',
    avatar: '',
    roles: [] as string[]
  });

  // 用户token
  const token = ref('');

  // 用户路由
  const routes = ref<RouteRecordRaw[]>([]);

  // 是否已获取菜单
  const hasGetMenus = ref(false);

  // 设置用户信息
  const setUserInfo = (info: any) => {
    Object.assign(userInfo, info);
    Cookies.set('userInfo', JSON.stringify(info));
  };

  // 设置token
  const setToken = (value: string) => {
    token.value = value;
    Cookies.set('token', value);
  };

  // 设置路由
  const setRoutes = (routeList: RouteRecordRaw[]) => {
    routes.value = routeList;
  };

  // 设置菜单获取状态
  const setHasGetMenus = (value: boolean) => {
    hasGetMenus.value = value;
  };

  // 登录
  const login = async (username: string, password: string) => {
    // 这里应该是调用登录接口
    // 模拟登录成功
    const token = 'mock-token';
    const userInfo = {
      id: '1',
      name: 'Admin User',
      avatar: '',
      roles: ['admin']
    };

    setToken(token);
    setUserInfo(userInfo);

    return { token, userInfo };
  };

  // 登出
  const logout = () => {
    token.value = '';
    Object.assign(userInfo, {
      id: '',
      name: '',
      avatar: '',
      roles: []
    });
    routes.value = [];
    hasGetMenus.value = false;

    Cookies.remove('token');
    Cookies.remove('userInfo');

    // 重定向到登录页
    router.push('/login');
  };

  // 获取用户信息
  const getUserInfo = async () => {
    // 这里应该是调用获取用户信息接口
    // 如果已经有用户信息，直接返回
    if (userInfo.id) {
      return userInfo;
    }

    // 从cookie中获取用户信息
    const savedUserInfo = Cookies.get('userInfo');
    if (savedUserInfo) {
      const parsedUserInfo = JSON.parse(savedUserInfo);
      setUserInfo(parsedUserInfo);
      return parsedUserInfo;
    }

    // 如果没有用户信息，调用接口获取
    // 模拟获取用户信息
    const mockUserInfo = {
      id: '1',
      name: 'Admin User',
      avatar: '',
      roles: ['admin']
    };

    setUserInfo(mockUserInfo);
    return mockUserInfo;
  };

  return {
    userInfo,
    token,
    routes,
    hasGetMenus,
    setUserInfo,
    setToken,
    setRoutes,
    setHasGetMenus,
    login,
    logout,
    getUserInfo
  };
});
